package org.next.tesigiulia.utils;

import twitter4j.*;

import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TwitterArea {
    private Twitter twitter;
    private final double latitude;
    private final double longitude;
    private final double radius;
    private boolean go = false;
    private Query query;
    private Runnable myRunnable;
    private HashMap<Long, Status> statusHashMap = new HashMap<Long, Status>();


    public TwitterArea(Twitter twitter, double latitude, double longitude, double radius) {
        this.twitter = twitter;
        this.latitude = latitude;
        this.longitude = longitude;
        this.radius = radius;

        myRunnable = new Runnable() {
            @Override
            public void run() {
                go = true;
                while (go) {
                    try {
                        fetchResults();
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage());
                    } catch (TwitterException e) {
                        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage());
                        go = false;
                    }
                }
            }
        };
    }

    public void start() {
        GeoLocation geoLocation = new GeoLocation(latitude, longitude);

        query = new Query();
        query.setGeoCode(geoLocation, radius, Query.KILOMETERS);


        Thread thread = new Thread(myRunnable);
        thread.start();
    }

    private void fetchResults() throws TwitterException {
        QueryResult results = twitter.search(query);
        if (results == null) {
            return;
        }
        for (Status status : results.getTweets()) {
            if (!statusHashMap.containsKey(status.getId()) && status.getGeoLocation() != null) {
                TwitterEvent twitterEvent = new TwitterEvent();
                twitterEvent.setStatus(status);
                MyEventBus.getInstance().getEventBus().post(twitterEvent);
                statusHashMap.put(status.getId(), status);
            }
        }
    }

    public void stop() {
        go = false;
    }

    public boolean isStarted() {
        return go;
    }
}

